package com.lv.phuotbacnam.ui.fragment;

import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Environment;

import com.lv.phuotbacnam.bl.log.Logger;
import com.lv.phuotbacnam.bl.utils.ImageLoaderCus;
import com.lv.phuotbacnam.ui.navigation.NavigationController;

/**
 * App base fragment
 */
public class BaseFragment extends Fragment {

	/* Navigation controller to use */
	private NavigationController navigationController;

	/* use to display image from url */
	public ImageLoaderCus imageLoader;

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		imageLoader = new ImageLoaderCus(getActivity());

		try {
			navigationController = (NavigationController) activity;
		} catch (ClassCastException cce) {
			Logger.logError(
					"The activity is not an instance of a NavigationController",
					cce);
		}
		applyStyles();
	}

	@Override
	public void onDetach() {
		super.onDetach();
		navigationController = null;
	}

	/**
	 * Intercept the back button press
	 * 
	 * @return true if the fragment consumed the event
	 */
	public boolean onBackPressed() {
		return false;
	}

	/**
	 * Get the navigation controller
	 * 
	 * @return App navigation controller
	 */
	public NavigationController getNavigationController() {
		return navigationController;
	}

	/**
	 * Refresh the UI
	 */
	public void refresh(Bundle arguments) {
		// do nothing - override it to refresh te screen
	}

	/**
	 * Style the app action bar. Should be ovveriden by fragments which change
	 * the action bar appearance
	 */
	public void applyStyles() {
		// do nothing - override it to be able to style the action bar
		// accordingly
	}

	public void runDelayed(final Runnable runnable, long whenTimeMillis) {
		new CountDownTimer(whenTimeMillis, whenTimeMillis) {
			@Override
			public void onTick(long millisUntilFinished) {

			}

			@Override
			public void onFinish() {
				runnable.run();
			}
		}.start();
	}

	/**
	 * To check if SdCard is Readable or not
	 * 
	 * @return
	 */
	private boolean isSdReadable() {
		boolean mExternalStorageAvailable = false;
		try {
			String state = Environment.getExternalStorageState();
			if (Environment.MEDIA_MOUNTED.equals(state)) {
				// We can read and write the media
				mExternalStorageAvailable = true;
			} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
				// We can only read the media
				mExternalStorageAvailable = true;
			} else
				mExternalStorageAvailable = false;
		} catch (Exception ex) {
			Logger.logMessage("Error when check SdCard is readable or not: "
					+ ex.getMessage());
		}
		return mExternalStorageAvailable;
	}
}
